from utils.data_split import DataSplitUtil
from config.config import *
import pandas as pd


data = pd.read_csv(clinic_data_path)
dp = DataSplitUtil(split_random_state_list[0])
train_df,_ = dp.get_train_test_df(data)



import pandas as pd
import numpy as np
import statsmodels.api as sm
from sklearn.impute import SimpleImputer

def univariate_logistic_regression(df, target_col=target_column):
    results = []

    # 分开连续和分类变量
    for col in df.columns:
        if col in exclude_columns:
            continue
        
        X = df[[col]].copy()
        y = df[target_col]

        # --- 缺失值插补 ---
        if X[col].dtype in [np.float64, np.int64]:
            imputer = SimpleImputer(strategy='median')
        else:
            imputer = SimpleImputer(strategy='most_frequent')
        X[col] = imputer.fit_transform(X[[col]])


        # --- 添加截距 ---
        X_sm = sm.add_constant(X)
        # --- Logistic 回归 ---
        try:
            model = sm.Logit(y, X_sm).fit(disp=0)
            for var in X_sm.columns[1:]:
                coef = model.params[var]
                se = model.bse[var]
                or_val = np.exp(coef)
                ci_lower = np.exp(coef - 1.96 * se)
                ci_upper = np.exp(coef + 1.96 * se)
                p = model.pvalues[var]
                results.append({
                    'Feature': var,
                    'OR': round(or_val, 3),
                    '95% CI': f"[{ci_lower:.3f}, {ci_upper:.3f}]",
                    'p': round(p, 4)
                })
        except Exception as e:
            # 回归失败时填NA
            results.append({
                'Feature': col,
                'OR': 'NA',
                '95% CI': 'NA',
                'p': 'NA'
            })
    
    return pd.DataFrame(results)

# 使用示例
df_uni = univariate_logistic_regression(train_df, target_col=target_column)
df_uni.to_csv(opj(clinic_analysis_result_path,'univariate_logistic_results.csv'), index=False)
print(df_uni)